package com.wumeng.dynamicmultidatabase.modules.user.controller;

import com.wumeng.dynamicmultidatabase.config.DBContextHolder;
import com.wumeng.dynamicmultidatabase.config.DBTypeEnum;
import com.wumeng.dynamicmultidatabase.modules.user.dao.User;
import com.wumeng.dynamicmultidatabase.modules.user.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Timestamp;


/**
 * @author wumeng 2022/6/8 4:35 下午
 */
@RestController
@RequestMapping("/user")
public class UserController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private UserService userService;

    // query_user?id=1 -> main DB
    // query_user?id=1&client=client-a -> Client A DB
    // query_user?id=1&client=client-b -> Client B DB
    @RequestMapping(value = "/query_user", method = RequestMethod.GET)
    public User queryUserById(int id, String client) {

        switch (client) {
            case "client-a":
                DBContextHolder.setCurrentDb(DBTypeEnum.CLIENT_A);
                break;
            case "client-b":
                DBContextHolder.setCurrentDb(DBTypeEnum.CLIENT_B);
                break;
        }
        logger.info("查询id = " + id + " client = " + client);
        return this.userService.queryUserById(id);
    }

    @RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
    public String deleteUserById(int id, String client) {
        switch (client) {
            case "client-a":
                DBContextHolder.setCurrentDb(DBTypeEnum.CLIENT_A);
                break;
            case "client-b":
                DBContextHolder.setCurrentDb(DBTypeEnum.CLIENT_B);
                break;
        }
        this.userService.deleteById(id);
        logger.info("删除id" + id);
        return "删除成功";
    }

    @GetMapping("/addUser/{id}")
    public String addUser(@PathVariable(value = "id") Integer id, @RequestParam(value = "name") String name, @RequestParam(value = "client") String client) {

        switch (client) {
            case "client-a":
                DBContextHolder.setCurrentDb(DBTypeEnum.CLIENT_A);
                break;
            case "client-b":
                DBContextHolder.setCurrentDb(DBTypeEnum.CLIENT_B);
                break;
        }
        User user = new User();
        user.setName(name);
        user.setCreate_time(new Timestamp(System.currentTimeMillis()));
        int addCode = this.userService.add(user);
        logger.info("id " + id + "add code " + addCode);
        return "添加成功";
    }


}


